package com.uenpay.im.ui.old.activity.group;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.listener.OnHttpRequestTextListener;
import com.qiyunxin.android.http.net.HttpInvokeItem;
import com.qiyunxin.android.http.net.HttpRequestAsyncTaskQueue;
import com.qiyunxin.android.http.net.HttpRequestType;
import com.qiyunxin.android.http.net.HttpTextAsyncTask;
import com.qyx.android.database.GroupMemberManager;
import com.qyx.android.entity.GroupMemberEntity;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.chat.ActivityHandle;
import com.uenpay.im.adapter.GroupMemberAdapter;
import com.uenpay.im.callback.IOnBottomDialogListener;
import com.uenpay.im.callback.IRemoveGroupMemberListener;
import com.uenpay.im.invokeitems.chat.GetGroupMembersListInvokeItem;
import com.uenpay.im.weight.DialogUtility;
import com.uenpay.util.app.base.BaseActivity;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Locale;

/**
 * 群成员
 *
 * @author SL
 * @copyRight http://www.qiyunxin.com
 */
public class GroupMemberActivity extends BaseActivity {

    private EditText search_et;
    private TextView no_data_text;
    private ListView mListView;
    private GroupMemberAdapter mGroupMemberAdapter;
    private String group_id;
    private ArrayList<GroupMemberEntity> mArrayList = new ArrayList<GroupMemberEntity>();
    private GroupMemberManager mGroupMemberManager = new GroupMemberManager();
    private TextView right_TextView, title_TextView;
    private int type = -1;
    private String creator_cust_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_group;
    }

    @Override
    public void initView(View view) {
        if (getIntent().hasExtra("type")) {
            type = getIntent().getIntExtra("type", -1);
        }
        group_id = getIntent().getStringExtra("group_id");
        creator_cust_id = getIntent().getStringExtra("creator_cust_id");
        initView();
        initListener();
        showMembers();
        getGroupMembers();
    }

    protected void initView() {
        right_TextView = (TextView) findViewById(R.id.title_right_tv);
        title_TextView = (TextView) findViewById(R.id.title_textview);
        right_TextView.setVisibility(View.GONE);
        mListView = (ListView) findViewById(R.id.listView);
        no_data_text = (TextView) findViewById(R.id.no_data_text);
        search_et = (EditText) findViewById(R.id.search_et);
    }

    protected void initListener() {
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {

                GroupMemberEntity GroupMemberEntity = (GroupMemberEntity) arg0
                        .getAdapter().getItem(arg2);
                if (GroupMemberEntity != null) {
                    if (type == 1) {
                        setNewManagerDialog(GroupMemberEntity.cust_id + "",
                                GroupMemberEntity.nick_name);
                    } else if (type == 2) {
                        Intent intent = new Intent();
                        intent.putExtra("cust_name",
                                GroupMemberEntity.nick_name);
                        setResult(RESULT_OK, intent);
                        finish();
                    } else {
                        ActivityHandle.startUserDetailActivity(
                                GroupMemberActivity.this,
                                GroupMemberEntity.cust_id + "");
                    }
                }
            }
        });
        search_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                searchTextInUsers(s);
            }
        });
    }

    private void searchTextInUsers(CharSequence text) {
        if (text != null && text.length() > 0) {
            if (TextUtils.isEmpty(text)) {
                no_data_text.setVisibility(View.GONE);
                return;
            }
            ArrayList<GroupMemberEntity> tempMembers = new ArrayList<GroupMemberEntity>();
            for (GroupMemberEntity mGroupMemberEntity : mArrayList) {
                String charIndex = mGroupMemberEntity.nick_name;
                if (mGroupMemberEntity.nick_name.toLowerCase(
                        Locale.getDefault()).contains(
                        text.toString().toLowerCase(Locale.getDefault()))
                        || charIndex.contains(text.toString().toLowerCase(
                        Locale.getDefault()))) {
                    tempMembers.add(mGroupMemberEntity);
                }
            }
            if (tempMembers.size() > 0) {
                no_data_text.setVisibility(View.GONE);
                mGroupMemberAdapter = new GroupMemberAdapter(
                        GroupMemberActivity.this, tempMembers);
                mListView.setAdapter(mGroupMemberAdapter);
            } else {
                mListView.setVisibility(View.GONE);
                no_data_text.setVisibility(View.VISIBLE);
            }
        } else {
            mListView.setVisibility(View.VISIBLE);
            mGroupMemberAdapter = new GroupMemberAdapter(
                    GroupMemberActivity.this, mArrayList);
            mListView.setAdapter(mGroupMemberAdapter);
            no_data_text.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (myBroadcastReceiver != null) {
            IntentFilter mIntentFilter = new IntentFilter();
            mIntentFilter.addAction(BroadcastAction.GET_TALKDETAIL_ACTION);
            registerReceiver(myBroadcastReceiver, mIntentFilter);
        }
    }

    private void showMembers() {
        mArrayList = queryMember();
        if (type == 1) {
            for (int i = 0; i < mArrayList.size(); i++) {
                if ((mArrayList.get(i).cust_id + "").equals(IMApplication
                        .getCustId())) {
                    mArrayList.remove(i);
                    break;
                }
            }
        }
        mGroupMemberAdapter = new GroupMemberAdapter(this, mArrayList);
        mListView.setAdapter(mGroupMemberAdapter);
        if (type == 1) {
            title_TextView.setText(getResources().getString(
                    R.string.choose_group_new_manager));
        } else {
            title_TextView.setText(MessageFormat.format(getResources()
                    .getString(R.string.group_member), mArrayList.size()));
        }
    }

    /**
     * @return
     */
    private ArrayList<GroupMemberEntity> queryMember() {

        ArrayList<GroupMemberEntity> list = new ArrayList<GroupMemberEntity>();

        list = mGroupMemberManager.queryAll(Long.valueOf(group_id));
        if (list.size() == 0) {
            GroupMangerHandler groupMangerHandler = new GroupMangerHandler();
            groupMangerHandler.getGroupDetail(group_id, null);

        }
        return list;
    }

    public BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction()
                    .equals(BroadcastAction.GET_TALKDETAIL_ACTION)) {
                String status = intent.getStringExtra("status");
                Message msg = myHandler.obtainMessage();
                msg.obj = status;
                msg.what = 0;
                myHandler.sendMessage(msg);
            }
        }

    };

    protected void onDestroy() {
        if (myBroadcastReceiver != null) {
            unregisterReceiver(myBroadcastReceiver);
        }
        super.onDestroy();
    }

    ;

    private void setNewManagerDialog(final String cust_id,
                                     final String cust_name) {

        DialogUtility.showDialog(GroupMemberActivity.this, MessageFormat
                        .format(getResources()
                                .getString(R.string.set_new_group_manager), cust_name),
                R.string.sure, R.string.cancel, true,
                new IOnBottomDialogListener() {

                    @Override
                    public void onClicked() {
                        setGroupNewManager(cust_id);
                    }
                });

    }

    private void setGroupNewManager(String cust_id) {
        GroupMangerHandler groupMangerHandler = new GroupMangerHandler();
        groupMangerHandler.setGroupNewManager(group_id, cust_id,
                new IRemoveGroupMemberListener() {

                    @Override
                    public void onRemoveGroupMemberResult(int status) {
                        if (status == HttpInvokeResultCode.RESULT_OK) {
                            setResult(RESULT_OK);
                            finish();
                        }
                    }
                });
    }

    /**
     * 获取群成员
     */
    private void getGroupMembers() {
        GetGroupMembersListInvokeItem item = new GetGroupMembersListInvokeItem(
                group_id);
        HttpRequestAsyncTaskQueue
                .getInstance()
                .AddTask(
                        new HttpTextAsyncTask(item)
                                .SetRequestType(HttpRequestType.SERVER_ONLY),
                        new OnHttpRequestTextListener() {

                            @Override
                            public void OnFail(boolean isCache, String reason) {
                                IMApplication.showToast(reason);
                            }

                            @Override
                            public void OnProgress(long total_bytes,
                                                   long downloaded_bytes) {
                            }

                            @Override
                            public void OnSuccess(HttpInvokeItem item,
                                                  boolean isCache, String cacheFilePath) {
                                GetGroupMembersListInvokeItem.GetGroupMembersListInvokeItemResult result = ((GetGroupMembersListInvokeItem) item)
                                        .getOutput();
                                if (result != null
                                        && result.status == HttpInvokeResultCode.RESULT_OK) {
                                    // TODO
                                    updateGroupMembers(result.participants);
                                    mGroupMemberAdapter = new GroupMemberAdapter(
                                            GroupMemberActivity.this,
                                            result.participants);
                                    mListView.setAdapter(mGroupMemberAdapter);
                                }
                            }
                        });

    }

    @Override
    public void onBackPressed() {
        finish();
        super.onBackPressed();
    }

    private Handler myHandler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 0) {
                if (msg.obj.equals("success")) {
                    showMembers();
                }
            }
            return false;
        }
    });

    private void updateGroupMembers(
            final ArrayList<GroupMemberEntity> _ArrayList) {
        if (TextUtils.isEmpty(creator_cust_id) || _ArrayList == null
                || _ArrayList.size() <= 0) {
            return;
        }

        if (!TextUtils.isEmpty(group_id))
            mGroupMemberManager.deleteGroupAllMembers(Long.valueOf(group_id));
        new Thread(new Runnable() {

            @Override
            public void run() {
                for (GroupMemberEntity p : _ArrayList) {
                    p.group_id = Long.valueOf(group_id);
                    if (p.cust_id == Long.valueOf(creator_cust_id)) {
                        p.role = "1";
                    } else {
                        p.role = "0";
                    }
                    mGroupMemberManager.insertOrUpdateGroupMember(p);
                }
            }
        }).start();
    }

}
